<template>
	<div class="wrap update">
		<div class="page-title">
			<h3>系统升级</h3>
		</div>
		<div class="table-wrap">
			<table style="margin: 0 auto;">
				<thead class="thead-bottom-line">
					<tr>
						<th style="width: 100px;">升级内容</th>
						<th style="width: 350px;">版本内容</th>
						<th style="width: 250px;">选择文件</th>
						<th style="width: 300px;">上传进度</th>
						<th style="width: 100px;">状态</th>
						<th style="width: 100px;">操作</th>
					</tr>
				</thead>
				<tbody>
					<tr :class="accredit=='valid'?'':'gary'">
						<td >系统版本</td>
						<td >{{ sysVersion ? sysVersion : "-"}}</td>
						<td>
							<input type="text" v-model="vsfilepath" class="styleinput" disabled="true" readonly placeholder="文件选择..."/>
							<label class="lookth sysVer" for="vsfile">浏览..</label>
							<input :disabled="accredit!='valid'" id="vsfile" type="file" v-on:change="vsShowpath()" class="vsfileinput"/>
						</td>
						<td>
							<div class="progress progress-striped active">
								<div class="vsbar progress-bar progress-bar-success" role="progressbar" aria-valuenow="num" aria-valuemin="0" aria-valuemax="100">
								</div>
							</div>
						</td>
						<td  class="vs-statu">准备</td>
						<td >
							<button id="vsbtn" :disabled="accredit!='valid'"  :class="(accredit=='valid')?'button button--aylen':''" @click="vsUpload()" >升级</button>
						</td>
					</tr>		
					<tr>
						<td rowspan="11">授权文件</td>
						<td >设备识别号：<p>{{acrt.device_id ? acrt.device_id : '-'}}</p></td>
						<td rowspan="11">
							<input type="text" v-model="pwfilepath" class="styleinput" disabled="true" readonly placeholder="文件选择..."/>
							<label class="lookth certfl" for="pwfile">浏览..</label>
							<input id="pwfile" type="file" v-on:change="pwShowpath()" class="pwfileinput" />
						</td>
						<td rowspan="11">
							<div class="progress progress-striped active">
								<div class="pwbar progress-bar progress-bar-success" role="progressbar" aria-valuenow="num" aria-valuemin="0" aria-valuemax="100">
								</div>
							</div>
						</td>
						<td rowspan="11"  class="pw-statu">准备</td>
						<td rowspan="11"><button id="pwbtn" @click="pwUpload()"  class="button button--aylen">升级</button></td>
					</tr>
					<tr>
						<td>
							授权类型：
							<span v-if='acrt.type=="official"'>正式</span>
							<span v-else-if='acrt.type=="test"'>测试</span>
							<span v-else>-</span>
						</td>
					</tr>
					<tr>
						<td>接入主机数：{{acrt.max_hosts ? acrt.max_hosts+'个' : '-'}}</td>
					</tr>
					<tr>
						<td>网管语言：<span v-if='acrt.lang=="chinese"'>中文</span><span v-else>{{acrt.lang ? acrt.lang : '-'}}</span></td>
					</tr>
					<tr>
						<td>授权日期：<span>{{getLocalTime(acrt.start_time) ? getLocalTime(acrt.start_time) : '-'}} </span></td>

					</tr>
					<tr>
						<td>授权有效期：截止至<span>{{getLocalTime(acrt.end_time) ? getLocalTime(acrt.end_time) : '-' }} </span></td>
					</tr>
					<tr>
						<td>授权用户：<p>{{acrt.user ? acrt.user : "-"}}</p></td>
					</tr>
					<tr>
						<td>备注：<p>{{acrt.desc ? acrt.desc : '-'}}</p></td>
					</tr>
					<tr>
						<td>授权厂家：<p>{{acrt.licence_owner ? acrt.licence_owner : '-'}}</p></td>
					</tr>
					<tr>
						<td>版权所有：<p>{{acrt.copy_right ? acrt.copy_right : '-'}}</p></td>
					</tr>
				</tbody>
			</table>
			<p v-if="accredit=='expired'" class="notice">授权文件已过期，请更新授权文件！</p>
			<p v-if="accredit!='expired'&&accredit!='valid'" class="notice">授权文件{{showtype}}，请升级授权文件！</p>

		</div>
		<!-- <Modals :id ="'confirm'" :title ="'提示'"   @modalEvent ="sysReboot()">
			<div slot ="modal_content">	
					<p style="font-size:16px;">授权文件升级成功！</p>
			</div>
		</Modals> -->
		<noticeModal :id="'confirm'" :title="'提示'" :status="'ok'" :Msg="'授权文件升级成功！'">
			<div slot="modal_footer">	
				<div class="modal-footer">  
					<template>
					   <button class="sure-btn button button--aylen" data-dismiss="modal" @click="sysReboot">确认</button>	                 					
					</template>		                     
				</div>
			</div>
		</noticeModal>
		<noticeModal :id="'notice'" :title="'提示'" :status ="requestStatus" :errorMsg="errorMsg" :Msg="msg">
			<div slot="modal_footer">	
				<div class="modal-footer">  
					<template v-if="types=='reup'"></template>
					<template v-else>
					   <button class="sure-btn button button--aylen" data-dismiss="modal" @click="vsCancel">确认</button>	                 					
					</template>		                     
				</div>
			</div>
		</noticeModal>
	</div>
</template>
<script>
	import SystemService from 'services/systemService'
	import noticeModal from 'components/common/noticeModal'
	import Modals from 'components/common/Modals'
	export default {
		components: {
			noticeModal,
			Modals
		},
		computed:{
			accredit: function() {
				return this.$store.state.cert.status
			},
			acrt: function() {
				return this.$store.state.cert
			},
			showtype: function() {
				let type=''
				switch (this.$store.state.cert.status) {
					case 'missing':
						type='缺失'
						break;
					case 'device_not_match':
						type='和设备不匹配'
						break;
					case 'malform':
						type='内容格式错误'
						break;
					case 'type_error':
						type='类型错误'
						break;
					case 'unknown':
						type='状态未知'
						break;
					case 'uninit':
						type='未初始化'
						break;
					default:
						break;
				}
				return type
			}
    	},
		mounted() {
			this.getsysinfo()
		},
		data() {
			return {
				vsfilepath:"",
				pwfilepath:"",
				types:"reboot",
				code:"",
				status:true,
				sysVersion:"",
				msg:"",
				result:'',
				errorMsg:'',
				requestStatus:''
				// accredit:true
			}
		},
		methods: {
			reload() {
				location.reload()
			},
			popoverShow(ele,content) {//小弹窗
				$(ele).attr({
					'data-toggle': 'popover',
          'data-placement':"bottom",
					'data-content': content
				}).popover('show')
				setTimeout(function() {
					$(ele).popover('destroy')
				}, 2000)
			},
			getLocalTime(nS) {
				if (nS) {
					return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');
				} else {
					return null   
				}   
				  
			},
			getsysinfo() {
				SystemService.getSysinfo()
				.then((res) => {
					if (res.errcode === 0) {
						this.sysVersion = res['23']
					}
				})
			},
			vsUpload() {
				let upfile = document.getElementsByClassName('vsfileinput')[0].files[0]
				if (!upfile) {
					this.popoverShow(".sysVer","请先选择文件")
					return
				}
				$(".vs-statu").css("color","#56b070")
				$(".vs-statu").text("开始升级")
				$("#vsbtn").attr("disabled","true")
				$("#vsbtn").css("background","rgba(153, 153, 153, 0.52)")
				let fd = new FormData()
				fd.append('file',upfile)
				let _this = this
				$.ajax({
					url: "/services/v1_1/sys_conf/UploadImage.php",
					type: 'POST',
					data: fd,
					processData: false,//用来回避jquery对formdata的默认序列化，XMLHttpRequest会对其进行正确处理
					contentType: false,//设为false才会获得正确的conten-Type
					xhr: function() { //用以显示上传进度
						let xhr = $.ajaxSettings.xhr();
						xhr.onreadystatechange = function () {
							if (xhr.readyState === 4) {
								if (xhr.status != 200) {
									$(".vs-statu").text("请求超时")
									$(".vs-statu").css("color","red")
									$("#vsbtn").removeAttr("disabled")
									$("#vsbtn").css("background","#f5b72e")
									_this.errorMsg = "请求超时"
									_this.requestStatus = 'error'
									$("#notice").modal('show');
								}
							}
						};
						if (xhr.upload) {
							xhr.upload.addEventListener('progress', function(e) {
								$(".vsbar").css("width",Math.floor(e.loaded/e.total*100)+"%")
								if (e.loaded/e.total*100 < 100) {
									$(".vs-statu").css("color","#56b070")
									$(".vs-statu").text("正在上传")
								}
							}, false);
						}
						return xhr;
					},
					async: true  
				}).then(function(data) {  
					let res = jQuery.parseJSON(data);
					if (res.errcode === 0) {
						$(".vsbar").css("width","0")
						$(".vs-statu").css("color","#56b070")
						$(".vs-statu").text("上传成功")
						$("#vsbtn").removeAttr("disabled")
						$("#vsbtn").css("background","#f5b72e")
						_this.types="reboot",
						_this.requestStatus = 'ok'
						$("#notice").modal('show');
					} else {
						$(".vs-statu").css("color","red")
						$(".vs-statu").text(res.errorMessage)
						$("#vsbtn").removeAttr("disabled")
						$("#vsbtn").css("background","#f5b72e")
						_this.errorMsg = res.errorMessage
						_this.requestStatus = 'error'
						$("#notice").modal('show');
					}
				})  
			},
			vsCancel() {
				$(".vsbar").css("width","0")
				$(".pwbar").css("width","0")
				$(".vs-statu").css("color","#56b070")
				$(".vs-statu").text("准备")
				$(".pw-statu").text('准备')
				$(".pw-statu").css("color","#56b070")
				this.vsfilepath = ""
				this.pwfilepath=''
				document.getElementsByClassName('vsfileinput')[0].value = "";
				document.getElementsByClassName('pwfileinput')[0].value = "";

				if (this.errorMsg === '请登录！') {
					this.$router.push('/login')
				}
			},
			//授权文件部分暂无
			pwUpload() {
				let upfile = document.getElementsByClassName('pwfileinput')[0].files[0]
				if (!upfile) {
					this.popoverShow(".certfl","请先选择文件")
					return
				}
				$(".pw-statu").css("color","#56b070")
				$(".pw-statu").text("开始升级")
				$("#pwbtn").attr("disabled","true")
				$("#pwbtn").css("background","rgba(153, 153, 153, 0.52)")
				let fd = new FormData()
				fd.append('file',upfile)
				let _this=this
				$.ajax({
					url:"license/upload",
					type: 'POST',
					data: fd,
					processData: false,//用来回避jquery对formdata的默认序列化，XMLHttpRequest会对其进行正确处理
					contentType: false,//设为false才会获得正确的conten-Type
					xhr: function() { //用以显示上传进度
						let xhr = $.ajaxSettings.xhr();
						xhr.onreadystatechange = function () {
							if (xhr.readyState === 4) {
								if (xhr.status != 200) {
									$(".pw-statu").text("请求超时")
									$(".pw-statu").css("color","red")
									$("#pwbtn").removeAttr("disabled")
									$("#pwbtn").css("background","#f5b72e")

									_this.errorMsg = "请求超时"
									_this.requestStatus = 'error'
									$("#notice").modal('show');
								}
							}
						};
						if (xhr.upload) {
							xhr.upload.addEventListener('progress', function(e) {
								$(".pwbar").css("width",Math.floor(e.loaded/e.total*100)+"%")
								if (e.loaded/e.total*100 < 100) {
									$(".pw-statu").css("color","#56b070")
									$(".pw-statu").text("正在上传")
								}
							}, false);
						}
						return xhr;
					},
					async: true  
				}).then(function(res) {  
					if (res.errcode === 0) {
						$(".pw-statu").css("color","#56b070")
						$(".pw-statu").text("上传成功")
						_this.result=''
						_this.types='cart'
						
						$("#pwbtn").removeAttr("disabled")
						$("#pwbtn").css("background","#f5b72e")
						$("#confirm").modal('show')
					} else {
						$(".pw-statu").css("color","red")
						$(".pw-statu").text("上传失败")
						$("#pwbtn").removeAttr("disabled")
						$("#pwbtn").css("background","#f5b72e")

						_this.errorMsg = _this.$t('error_code.' + res.errcode)
						_this.requestStatus = 'error'
						$("#notice").modal('show');
					}
				})  
			},
			sysReboot() {
				$("#confirm").modal('hide')
			},
			vsShowpath() {
				this.vsfilepath = this.getFilename(".vsfileinput")
			},
			pwShowpath() {
				this.pwfilepath = this.getFilename(".pwfileinput")
			},
			getFilename(ele) {
				let fileName="";
				if (typeof(fileName) != "undefined") {  
					fileName = $(ele).val().split("\\").pop();
				} 
				return fileName
			}	
		}
	}
</script>
